Kotlin Koans 23 FlatMap

目次

FlatMap (Playground)

Description

Implement Customer.getOrderedProducts() and Shop.getAllOrderedProducts() using flatMap.

flatMap を使用して、Customer.getOrderedProducts() および Shop.getAllOrderedProducts() を実装してください。

val result = listOf("abc", "12").flatMap { it.toCharList() }
result == listOf('a', 'b', 'c', '1', '2')

Code

// Return all products this customer has ordered
val Customer.orderedProducts: Set<Product> get() {
    return orders.flatMap { it.products }.toSet()
}

// Return all products that were ordered by at least one customer
val Shop.allOrderedProducts: Set<Product> get() {
    return customers.flatMap { it.orderedProducts }.toSet()
}

Memo

← Posts